package com.hxh.generater.springBoot.util.methodParse;

import java.util.ArrayList;
import java.util.List;

/**
 * @author HXH
 * @description:   处理重复校验的行
 * @date  2024/3/12
 **/
public class ProcessRepeatLine {
    public static final String REPLACE_KEY_WORD = "#";
    public static final String CHECK_REPEAT_PREFIX_KEY = REPLACE_KEY_WORD + "重复校验" + REPLACE_KEY_WORD;
    // 重复校验的key
    private static final List<String> CHECK_REPEAT_KEY_LIST = new ArrayList<>();
    static {
        //默认校验
        CHECK_REPEAT_KEY_LIST.add("import");
        CHECK_REPEAT_KEY_LIST.add("@Autowired");
        CHECK_REPEAT_KEY_LIST.add("@Resource");
        CHECK_REPEAT_KEY_LIST.add("@Value");
    }

    /**
     * 是否需要校验重复
     * @param line
     * @return
     */
    private static boolean needCheckRepeat(String line) {
        for (String s : CHECK_REPEAT_KEY_LIST) {
            if (line.trim().startsWith(s) && !line.trim().equals(s)) {
                return true;
            }
        }
        return false;
    }

    List<String> repeatList = new ArrayList<>();

    /**
     * 处理一行 去掉重复校验
     * @param line
     * @return
     */
    public String processOneLine(String line) {
        if (line.trim().contains(CHECK_REPEAT_PREFIX_KEY) || needCheckRepeat(line)) {
            if (line.contains("\n")) {
                line = line.replaceAll("\r\n", "\n");
                String[] lines = line.split("\n");
                StringBuilder repeatLines = new StringBuilder();
                for (String s : lines) {
                    if (!s.contains(CHECK_REPEAT_PREFIX_KEY) && !needCheckRepeat(s)) {
                        repeatLines.append(s).append("\n");
                        continue;
                    }
                    s = s.replaceAll(CHECK_REPEAT_PREFIX_KEY, "");
                    if (!repeatList.contains(s.trim())) {
                        repeatLines.append(s).append("\n");
                        repeatList.add(s.trim());
                    }
                }
                line = repeatLines.toString();
            } else {
                line = line.replaceAll(CHECK_REPEAT_PREFIX_KEY, "");
                if (repeatList.contains(line.trim())) {
                    line = "";
                } else {
                    repeatList.add(line.trim());
                }
            }
        }
        return line;
    }


}
